const {PDFDocument, degrees} = require("pdf-lib");
const {writeFileSync, readFileSync} = require("fs");

async function PDFWatermark(options) {
    const {text_arr, pdf_path, page_num, image_arr, output_dir} = options;
    if (!pdf_path) {
        throw Error('Please add pdf_path in options.');
    }
    // load pdf
    const document = await PDFDocument.load(readFileSync(pdf_path));
    //   get pages and number of pages
    const pages = document.getPages();
    const numberOfPages = pages.length;

    if (page_num && page_num > 0 && page_num > numberOfPages) {
        console.error('pdf watermark page num invalid ', page_num, numberOfPages);
        return null;
    }
    // loop throgh all pages
    if (text_arr && Array.isArray(text_arr)) {
        for (let a = 0; a < text_arr.length; a++) {
            for (let i = 0; i < numberOfPages; i++) {
                if (i + 1 === text_arr[a].page_num) {
                    const page = pages[i];
                    const {width, height} = page.getSize();

                    // diagonally rotate text
                    /* if (text[a].diagonally == true) {
                       textOption.rotate = degrees(-45);
                       textOption.x = width / 2 - text.length * 9;
                       textOption.y = height / 2 + 200;
                       textOption.size = 50;
                     }*/

                    // text watermark
                    await page.drawText(text_arr[a].text, {
                        x: text_arr[a].x, // center with left padding for text
                        y: text_arr[a].y,
                        size: text_arr[a].size | 12,
                        opacity: text_arr[a].opacity || 0.6,
                        ...text_arr[a],
                    });
                }
            }
        }
    }
    // image watermark
    if (image_arr && Array.isArray(image_arr)) {
        // load image
        for (let a = 0; a < image_arr.length; a++) {
            const emblemImageBytes = readFileSync(image_arr[a].url);
            const image = await document.embedPng(emblemImageBytes);
            const pngDims = image.scale(0.5);
            // loop throgh all pages
            for (let i = 0; i < numberOfPages; i++) {
                if (i + 1 === image_arr[a].page_num) {
                    const page = pages[i];
                    const {width, height} = page.getSize();

                    // diagonally rotate text
                    if (image_arr[a].diagonally == true) {
                        //imageOption.rotate = degrees(-45);
                        image_arr[a].x = image_arr[a].x - 10;//width / 2;
                        image_arr[a].y = image_arr[a].y + 10//height / 2 + 200;
                    }
                    await page.drawImage(image, {
                        x: image_arr[a].x,//width / 2 - pngDims.width / 2 + 15,
                        y: image_arr[a].y,//height / 2 - pngDims.height - 20,
                        width: image_arr[a].width,//pngDims.width,
                        height: image_arr[a].height,//pngDims.height,
                        opacity: image_arr[a].opacity || 0.8,
                        ...image_arr[a],
                    });
                }

            }
        }
    }

    // write to file
    writeFileSync(output_dir || pdf_path, await document.save());
    return output_dir;
}

// (async function () {
//   await PDFWatermark({
//     pdf_path: '/Users/mac/Downloads/2022-08-27-d56aa144-f5a4-4f10-885d-2537e4e880f7.pdf',//"/Users/mac/Downloads/2022-08-27-d56aa144-f5a4-4f10-885d-2537e4e880f7.pdf",
//         image_arr: [{
//             url:'/Users/mac/Downloads/111.png',
//             size: 30,
//             opacity: 0.8,
//             x:404.0344103519778,
//             y:674.325508059829,
//             width:55.530060693534814,
//             height:54.530060693534814,
//             diagonally:true
//         },{
//             url:'/Users/mac/Downloads/222.png',
//             size: 30,
//             opacity: 0.8,
//             x:304.0344103519778,
//             y:574.325508059829,
//             width:55.530060693534814,
//             height:54.530060693534814,
//             diagonally:true
//         }],
//         page_num:2,
//         output_dir: "/Users/mac/Downloads/output.pdf",
//         text_arr:[
//             {
//                 size:14,
//                 text:"2022-09-09",
//                 x:304.0344103519778,
//                 y:474.325508059829,
//             },
//             {
//                 size:14,
//                 text:"15618788747",
//                 x:304.0344103519778,
//                 y:404.325508059829,
//             }
//         ]
//   });
// })();

module.exports = PDFWatermark;

